package middleware

import (
	"Short_chain_cats/util"
	"log"
	"net/http"
	"strings"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

// JWTAuth JWT 认证逻辑
func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.GetHeader("Authorization")
		if tokenString == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "request header without token"})
			return
		}
		tokenString = strings.TrimPrefix(tokenString, "Bearer ")
		token, _ := jwt.ParseWithClaims(tokenString, &util.Claims{}, func(token *jwt.Token) (interface{}, error) {
			return []byte(util.SecretKey), nil
		})
		if claims, ok := token.Claims.(*util.Claims); ok && token.Valid {
			// 确保正确设置 userID
			c.Set("userID", claims.UserID)
			c.Set("user_role", claims.UserRole)
		} else {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
			return
		}
		c.Next()
	}
}

// CasbinMiddleware Casbin权限控制逻辑
func CasbinMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 检查是否能够获取到 userID
		userID, _ := c.Get("userID")
		userRole, _ := c.Get("user_role")
		if userID == 0 {
			log.Printf("UserID is not set or is zero")
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "状态未授权"})
			return
		}
		path := c.Request.URL.Path
		method := c.Request.Method
		flag, err := util.Enforcer.Enforce(userRole, path, method)
		if err != nil {
			log.Printf("Casbin enforce error: %v", err)
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "内部服务器错误"})
			return
		}
		if flag {
			c.Next()
		} else {
			// 打印调试信息
			log.Printf("Casbin enforce denied: userID=%d, userRole=%s, path=%s, method=%s", userID, userRole, path, method)
			c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "用户禁止访问"})
		}
	}
}

func CorsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	}
}

// SecurityMiddleware 安全中间件，用于设置安全相关的 HTTP 头
func SecurityMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("X-Content-Type-Options", "nosniff")
		c.Writer.Header().Set("X-Frame-Options", "DENY")
		c.Writer.Header().Set("X-XSS-Protection", "1; mode=block")
		c.Writer.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
		c.Next()
	}
}

//// CSRFMiddleware CSRF 保护中间件
//func CSRFMiddleware() gin.HandlerFunc {
//	return func(c *gin.Context) {
//		// 从请求头获取 CSRF token
//		csrfToken := c.GetHeader("X-CSRF-Token")
//		// 或者从 cookie 获取 CSRF token
//		// csrfToken, err := c.Cookie("csrf_token")
//		// if err != nil {
//		//     c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "missing CSRF token"})
//		//     return
//		// }
//		// 验证 CSRF token
//		if !isValidCSRFToken(csrfToken) {
//			c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "invalid CSRF token"})
//			return
//		}
//		c.Next()
//	}
//}
